<?php
namespace daswork\db;

use mysqli;

class Mysql
{
    //  数据库连接实例
    private static $instance = [];
    // 当前数据表名称（含前缀）
    protected $table = '';
    // 当前数据表名称（不含前缀）
    protected $name = '';
    // 当前数据表主键
    protected $pk;
    // 当前数据表前缀
    protected $prefix = '';
    // 查询参数
    protected $options = [];

    /**
     * 数据库初始化 并取得数据库类实例
     * @static
     * @access public
     * @param mixed         $config 连接配置
     * @param bool|string   $name 连接标识 true 强制重新连接
     * @return Connection
     * @throws Exception
     */
    public static function connect($config = [], $name = false) {
        if (false === $name) {
            $name = md5(serialize($config));
        }
        if (true === $name || !isset(self::$instance[$name])) {
            if (true === $name) {
                return self::createConnect($config['host'], $config['username'], $config['passwd'], $config['dbname']);
            } else {
                self::$instance[$name] = self::createConnect($config['host'], $config['username'], $config['passwd'], $config['dbname']);
            }
        }
        return self::$instance[$name];
    }

    /**
     * 新建连接
     */
    private static function createConnect($host, $username, $passwd, $dbname)
    {
        $mysqli = new mysqli($host, $username, $passwd, $dbname);
        if ($mysqli->connect_error) {
            throw new \Exception('Connect Error ' . $mysqli->connect_error , $mysqli->connect_errno);
        }
        $mysqli->set_charset('utf8');
        return $mysqli;
    }

    /**
     * 指定默认的数据表名（不含前缀）
     * @access public
     * @param string $name
     * @return $this
     */
    public function name($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * 指定默认数据表名（含前缀）
     * @access public
     * @param string $table 表名
     * @return $this
     */
    public function setTable($table)
    {
        $this->table = $table;
        return $this;
    }

    /**
     * 得到当前或者指定名称的数据表
     * @access public
     * @param string $name
     * @return string
     */
    public function getTable($name = '')
    {
        if ($name || empty($this->table)) {
            $name      = $name ?: $this->name;
            $tableName = $this->prefix;
            if ($name) {
                $tableName .= $name;
            }
        } else {
            $tableName = $this->table;
        }
        return $tableName;
    }
}